package com.qc.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qc.chat.ChatListMember;
import com.qc.common.DateUtil;
import com.qc.common.SMSClient;
import com.qc.common.Session;
import com.qc.common.StringUtil;
import com.qc.common.Util;
import com.qc.entity.ActivityTimeEntity;
import com.qc.entity.PointEntity;
import com.qc.entity.UserEntity;
import com.qc.entity.UserSecScheduleEntity;
import com.qc.entity.message.ChatMessageEntity;
import com.qc.serverlistener.CacheUtil;
import com.qc.service.ActivityTimeService;
import com.qc.service.UserService;

import net.sf.json.JSONObject;

/**
 * 活动 排行榜
 *
 */

@Controller
public class RankingController extends BaseController{

	@Resource
	private UserService userService;
	
	@Resource(name="activityTimeService")
	private ActivityTimeService activityTimeService;
	
	/**
	 * 跳转到 活动 排行榜
	 * @return
	 */
	@RequestMapping(value = "/toHuoDong", produces = "text/html;charset=UTF-8")
    public ModelAndView toHuoDong() {
        ModelAndView mav = new ModelAndView("/huodong/paihangbang");
        
        //周一
        String monday = DateUtil.monday2();
        
        //下周一日期
        String monday3 = DateUtil.monday3();
        
        //周日
        String sunday = DateUtil.sunday();
        
        mav.addObject("monday",monday);
        mav.addObject("monday3",monday3);
        mav.addObject("sunday",sunday);
        
        return mav;
    }
	
	/**
	 * 排行榜 本周
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/MobileGetListRanking", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetListRanking(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		
		UserSecScheduleEntity entity = (UserSecScheduleEntity) JSONObject.toBean(JSONObject.fromObject(p1), UserSecScheduleEntity.class);
		
		List<UserSecScheduleEntity> list =  new ArrayList<UserSecScheduleEntity>();
		
		String time = DateUtil.monday();
		if (1 == entity.getRankingState()) {
			
			list = userService.listRanking(time, "", entity.getPageNo(), entity.getPageSize());
			
		}else {
			
			String time2 = DateUtil.sunday2();
			
			list = userService.listRanking(time, time2, entity.getPageNo(), entity.getPageSize());
			
		}

		return returnSuccessResult(list);
	}
	
	/**
	 * 点赞数 加1
	 */
	@RequestMapping(value = "/MobilePointUpdateSave", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String MobilePointUpdateSave(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		UserSecScheduleEntity entity = (UserSecScheduleEntity) JSONObject.toBean(JSONObject.fromObject(p1), UserSecScheduleEntity.class);
		
		int count = userService.getPointCount(entity.getSsId(), userId);
		if (count == 0) {
			//评论数加一
			userService.updatePoint(entity.getSsId());
			
			PointEntity pointEntity = new PointEntity();
			
			pointEntity.setUserId(userId);
			pointEntity.setSsId(entity.getSsId());
			
			userService.savePoint(pointEntity);
			
			return returnSuccessResult("点赞成功");
			
		}else {
			return returnSuccessResult("已点赞");
		}
	}
	
	/**
	 * 分享活动 点赞 验证码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/toSenCode", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String toSenCode(HttpServletRequest request, HttpServletResponse response) {

		int code = Util.get6code();
        String userName = request.getParameter("userName");
        
        String sucess = "0";
            
        Boolean flag = SMSClient.send(userName, "您的注册验证码是"+code+"，为了保护您的账户安全，验证短信请勿转发给其他人。【圈城】");
        if (flag) {
            String codeStr = userService.getMobileCode(userName);
            if (codeStr != null && !codeStr.equals("")) {
                userService.updateCodeByMobile(userName, code+"");
            } else {
                userService.saveCode(userName, code+"");
            }
            sucess = "1";
        }else{
        	sucess = "0";
        }
        
		return sucess;
	}
	
	/**
	 * 分享 点赞 PC登录
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/toUserLongin", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String toUserLongin(HttpServletRequest request, HttpServletResponse response) throws SQLException {
		
		String userName = request.getParameter("userName");
        String phone_code = request.getParameter("phone_code");
        long ssId = Long.parseLong(request.getParameter("ssId"));
		
		String code = userService.getMobileCode(userName);
		if (code == null || !code.equals(phone_code)) {
			return "2";
		}
		
		String falg = "0";
		
		UserEntity userEntity = userService.getUserName(userName);
		
		//验证手机号是否存在
		if (StringUtil.isNotEmpty(userEntity.getUserName())) {
			
			falg = "1";
			
		}else {
			userEntity.setUserName(userName);
			userEntity.setCreatedTime(DateUtil.getCurrentSysTimestamp());
			userEntity.setNickname(Util.get8Code()+"");
			userEntity.setUserPwd("quancheng2017");
			
			long state = userService.register(userEntity);
			
			String token = Session.getMobileToken(state);
			userEntity.setToken(token);
			userEntity.setUserId(state);
			//处理内存
			CacheUtil.addUserInfo(userEntity);
			//保存token到数据库
			userService.saveTokenByUserId(state,token);
			
			//用客服默认给他发送一个消息
			ChatMessageEntity messageEntity = new ChatMessageEntity();

			messageEntity.setSenderId(1);//客服定死为1
			messageEntity.setContent("欢迎来到圈城，您有任何疑问都可以发消息给我哦!");
			messageEntity.setSendTime(DateUtil.getSysTimeout());
			messageEntity.setContentType(0);
			messageEntity.setSenderAvatar("");
			messageEntity.setSenderNickname("圈城客服");
			messageEntity.setCategory(3);
			
			messageEntity.setTargetId(state);
			//设置msg_id
			messageEntity.setMsgId(DateUtil.getSysTimestamp());
			ChatListMember.defaultSenderMessage(messageEntity);
			
			falg = "1";
			
		}
		
		int count = userService.getPointCount(ssId, userEntity.getUserId());
		if (count == 0) {
			//评论数加一
			userService.updatePoint(ssId);
			
			PointEntity pointEntity = new PointEntity();
			
			pointEntity.setUserId(userEntity.getUserId());
			pointEntity.setSsId(ssId);
			
			userService.savePoint(pointEntity);
			
		}
		
		userEntity.setPageTotal(count);
		
		request.getSession().setAttribute("userEntity", userEntity);
		
		return falg;
		
	}
	
	/**
	 * 获取 历史 排行时间
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/MobileGetListActivity", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String MobileGetListActivity(HttpServletRequest request, HttpServletResponse response) {

		List<ActivityTimeEntity> list = activityTimeService.listAllActivityTime(1, 10);

		return returnSuccessResult(list);
	}
	
	
}
